package com.gxa.weixing.pc.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.gxa.weixing.core.common.ExceptionCode;
import com.gxa.weixing.core.exception.BusinessException;
import com.gxa.weixing.core.pojo.Goods;
import com.gxa.weixing.core.pojo.GoodsDetail;
import com.gxa.weixing.core.pojo.GoodsImg;
import com.gxa.weixing.core.pojo.GoodsListVO;
import com.gxa.weixing.core.service.impl.BaseServiceImpl;
import com.gxa.weixing.core.util.VerifyParamUtil;
import com.gxa.weixing.pc.mapper.GoodsDetailMapper;
import com.gxa.weixing.pc.mapper.GoodsMapper;
import com.gxa.weixing.pc.service.GoodsDetailService;
import com.gxa.weixing.pc.service.GoodsImgService;
import com.gxa.weixing.pc.service.GoodsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lijianmin
 * @date 2022/01/06  16:49:51
 */
@Service("goodsService")
@Transactional(rollbackFor = Throwable.class)
public class GoodsServiceImpl extends BaseServiceImpl<Goods> implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private GoodsDetailMapper goodsDetailMapper;

    @Resource
    private GoodsDetailService goodsDetailService;

    @Resource
    private GoodsImgService goodsImgService;

    /**
     * 根据特定条件获取商品列表的方法
     *
     * @param map 条件
     *            name: 商品名称 模糊
     *            supplierName:供应商名称 模糊
     *            state:销售状态
     *            promotion:推广状态
     *            shopId: 门店编号  门店库存 - 商品选择需要此字段
     *            page: 页码
     *            size: 每页数据量
     * @return 返回信息
     */
    @Override
    public PageInfo<GoodsListVO> getGoodsList(Map<String, Object> map) throws Exception {
        // 获取分页参数
        Integer page = VerifyParamUtil.pageDefaultOneVerify(map.get("page"));
        Integer size = VerifyParamUtil.sizeDefaultFiveVerify(map.get("size"));

        // 开启分页
        PageMethod.startPage(page, size);
        // 获取其他字段 并进行非空判断
        String name = VerifyParamUtil.stringVerifyParam(map.get("name"));
        String supplierName = VerifyParamUtil.stringVerifyParam(map.get("supplierName"));
        Integer state = VerifyParamUtil.integerVerifyParam(map.get("state"));
        Boolean promotion = VerifyParamUtil.booleanVerifyParam(map.get("promotion"));
        Long shopId = VerifyParamUtil.longVerifyParam(map.get("shopId"));

        // 查询数据
        List<GoodsListVO> goodsList = goodsMapper.getGoodsList(name, supplierName, state, promotion, shopId);
        // 返回带分页的数据
        return PageInfo.of(goodsList);
    }

    /**
     * 根据特定条件获取门店库存列表的方法
     *
     * @param map 条件
     *            name: 商品名称 模糊
     *            state:销售状态
     *            shopGoodsState:销售状态
     *            shopName:门店名称
     *            page: 页码
     *            size: 每页数据量
     * @return 返回信息
     */
    @Override
    public PageInfo<Map<String, Object>> getShopGoodsList(Map<String, Object> map) throws BusinessException, ParseException {

        // 获取分页参数
        Integer page = VerifyParamUtil.pageDefaultOneVerify(map.get("page"));
        Integer size = VerifyParamUtil.sizeDefaultFiveVerify(map.get("size"));

        // 开启分页
        PageMethod.startPage(page, size);
        // 获取其他字段 并进行非空判断
        String name = VerifyParamUtil.stringVerifyParam(map.get("name"));
        Integer state = VerifyParamUtil.integerVerifyParam(map.get("state"));
        Integer shopGoodsState = VerifyParamUtil.integerVerifyParam(map.get("shopGoodsState"));
        String shopName = VerifyParamUtil.stringVerifyParam(map.get("shopName"));

        // 查询数据
        List<Map<String, Object>> shopGoodsList = goodsMapper.getShopGoodsList(name, state, shopGoodsState, shopName);

        // 循环遍历查询到的数据
        for (Map<String, Object> maps : shopGoodsList) {
            // 把修改时间替换为转换格式后的日期
            maps.put("updateTime", VerifyParamUtil.formatDate(maps.get("updateTime")));
        }

        // 返回带分页的数据
        return PageInfo.of(shopGoodsList);
    }

    @Override
    public List<GoodsListVO> getGoodsListByShopId(Long shopId) {
        List<GoodsListVO> goodsListVOS;
        if (shopId == null || shopId == 0) {
            goodsListVOS = goodsMapper.selectGoodsListByShopId();
        } else {
            goodsListVOS = goodsMapper.getGoodsListByShopId(shopId);
        }
        return goodsListVOS;
    }

    /**
     * 修改商品方法
     *
     * @param map 修改信息
     * @return 返回是否成功
     */
    @Override
    public void update(Map<String, Object> map) throws BusinessException {
        // 进行是否为空校验
        VerifyParamUtil.checkParams(map);

        // 先获取商品编号
        Long id = VerifyParamUtil.longVerifyParam(map.get("id"));

        // 将map转换为JSON字符串
        String jsonStr = JSONUtils.toJSONString(map);

        // 将JSON字符串转换为对象
        Goods goods = JSON.parseObject(jsonStr, Goods.class);
        GoodsDetail goodsDetail = JSON.parseObject(jsonStr, GoodsDetail.class);

        //获取到当前商品编号对应的商品详情编号 并装入新建商品详情对象
        System.out.println(goodsDetailMapper.selectByGoodsId(id).getId());
        goodsDetail.setGoodsId(id);


        // 进行修改操作
        Integer goodsUpdate = updateById(goods);
        Integer goodsDetailUpdate = goodsDetailService.updateById(goodsDetail);

        // 如果任意一个返回为0 则抛出异常进行回滚
        if (goodsUpdate <= 0 || goodsDetailUpdate <= 0) {
            throw new BusinessException(ExceptionCode.UPDATE_ERROR);
        }

        // // 商品对象
        // Goods goods = new Goods();
        // // 商品编号
        // goods.setId(id);
        // // 商品名称
        // goods.setName(VerifyParamUtil.stringVerifyParam(map.get("name")));
        // // 销售价格
        // goods.setPrice(VerifyParamUtil.bigDecimalVerifyParam(map.get("price")));
        // // 平台销售状态
        // goods.setState(VerifyParamUtil.integerVerifyParam(map.get("state")));
        //
        // //-----------------------原型图未展示的修改
        // // 商品原价 删除线
        // goods.setPrePrice(VerifyParamUtil.bigDecimalVerifyParam(map.get("prePrice")));
        // // 采购价格
        // goods.setPurchasePrice(VerifyParamUtil.bigDecimalVerifyParam(map.get("purchasePrice")));
        // // 商品描述
        // goods.setDesc(VerifyParamUtil.stringVerifyParam(map.get("desc")));
        // // 商品封面
        // goods.setImg(VerifyParamUtil.stringVerifyParam(map.get("img")));
        //
        // // 商品详情对象
        // GoodsDetail goodsDetail = new GoodsDetail();
        //
        // //获取到当前商品编号对应的商品详情编号 并装入新建商品详情对象
        // goodsDetail.setId(goodsDetailMapper.selectByGoodsId(id).getId());
        // // 总库存
        // goodsDetail.setInventory(VerifyParamUtil.integerVerifyParam(map.get("inventory")));
        // // 实际销售量
        // goodsDetail.setSold(VerifyParamUtil.integerVerifyParam(map.get("sold")));
        // // 剩余库存
        // goodsDetail.setSurplusInventory(VerifyParamUtil.integerVerifyParam(map.get("surplusInventory")));
        // // 推广
        // goodsDetail.setPromotion(VerifyParamUtil.booleanVerifyParam(map.get("promotion")));
        // // 修改时间后台设定
        // goodsDetail.setUpdateTime(new Date());
        //
        // //-----------------------原型图未展示的修改
        // // 规格
        // goodsDetail.setUnit(VerifyParamUtil.stringVerifyParam(map.get("unit")));
        // // 单件重量 单位为g
        // goodsDetail.setWeight(VerifyParamUtil.doubleVerifyParam(map.get("weight")));
        // // 商品虚拟已售量
        // goodsDetail.setSoldVirtual(VerifyParamUtil.integerVerifyParam(map.get("soldVirtual")));
        // // 商品详细介绍
        // goodsDetail.setIntroduce(VerifyParamUtil.stringVerifyParam(map.get("introduce")));
        // // 商品示例图
        // goodsDetail.setSampleImg(VerifyParamUtil.stringVerifyParam(map.get("sampleImg")));
        // // 供应商编号
        // goodsDetail.setSupplierId(VerifyParamUtil.longVerifyParam(map.get("supplierId")));
        // // 推广语
        // goodsDetail.setPromotionStatement(VerifyParamUtil.stringVerifyParam(map.get("promotionStatement")));

    }

    /**
     * 删除商品方法
     *
     * @param id 删除商品的编号
     */
    @Override
    public void delete(Long id) throws BusinessException {
        // 进行是否为空校验
        VerifyParamUtil.checkParams(id);

        // 删除商品
        Integer goodsDelete = deleteById(id);

        // 根据商品编号查询商品详情获取详情编号
        // 删除对应的商品详情
        Integer goodsDetailDelete = goodsDetailService.deleteById(goodsDetailMapper.selectByGoodsId(id).getId());
        if (goodsDelete <= 0 || goodsDetailDelete <= 0) {
            throw new BusinessException(ExceptionCode.DELETE_ERROR);
        }
    }

    /**
     * 添加商品方法
     *
     * @param map 添加信息
     */
    @Override
    public void add(Map<String, Object> map) throws BusinessException {
        // 进行是否为空校验
        VerifyParamUtil.checkParams(map);

        // 将map转换为JSON字符串
        String jsonString = JSONUtils.toJSONString(map);
        // 将JSON字符串转换为实体类
        Goods goods = JSON.parseObject(jsonString, Goods.class);
        GoodsDetail goodsDetail = JSON.parseObject(jsonString, GoodsDetail.class);


        // 进行添加操作
        Goods goodsAdd = insert(goods);
        // 进行校验 如果添加失败则抛出异常进行回滚
        if (goodsAdd.getId() == null) {
            throw new BusinessException(ExceptionCode.ADD_ERROR);
        }

        // 将添加返回的商品编号写入商品详情对象中
        goodsDetail.setGoodsId(goodsAdd.getId());
        // 添加时间设为默认
        goodsDetail.setAddTime(new Date());
        // 商品已售设为初始值0
        goodsDetail.setSold(0);
        // 剩余库存同步跟随总库存
        goodsDetail.setSurplusInventory(goodsDetail.getInventory());
        // 修改时间同步当前时间
        goodsDetail.setUpdateTime(new Date());

        System.out.println("***********Map转换为对象GoodsDetail*************");
        System.out.println(goodsDetail);
        System.out.println("***********Map转换为对象*************");

        // 进行添加操作
        GoodsDetail goodsDetailAdd = goodsDetailService.insert(goodsDetail);

        System.out.println(goodsAdd);
        System.out.println("--------------------");
        System.out.println(goodsDetailAdd);

        // 进行校验 如果添加失败则抛出异常进行回滚
        if (goodsDetailAdd.getId() == null) {
            throw new BusinessException(ExceptionCode.ADD_ERROR);
        }

        // 获取商品轮播图片
        Object imgs = map.get("images");
        VerifyParamUtil.checkParams(imgs);
        System.out.println(imgs);


        System.out.println("image..........................");
        //获取商品详情编号赋值到商品图片对象上


        List<String> images = (List<String>) imgs;

        for (String image : images) {
            GoodsImg goodsImg = new GoodsImg();
            goodsImg.setDetailId(goodsDetailAdd.getId());
            goodsImg.setImg(image);
            GoodsImg goodsImgAdd = goodsImgService.insert(goodsImg);
            if (goodsImgAdd == null || goodsImgAdd.getImgId() == null) {
                throw new BusinessException(ExceptionCode.ADD_ERROR);
            }

        }

    }


}
